package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private RoomAttrValueService roomAttrValueService;

    @Autowired
    private RoomFacilityService roomFacilityService;

    @Autowired
    private RoomLabelService roomLabelService;

    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;

    @Autowired
    private RoomLeaseTermService roomLeaseTermService;

    @Autowired
    private LeaseAgreementMapper leaseAgreementMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private AttrValueMapper attrValueMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private PaymentTypeMapper paymentTypeMapper;

    @Autowired
    private LeaseTermMapper leaseTermMapper;

    //保存或更新
    @Override
    public void saveOrUpdateRoomInfo(RoomSubmitVo roomSubmitVo) {
        Long id = roomSubmitVo.getId();
        if (id != null) {
            LambdaQueryWrapper<GraphInfo> graphVoWrapper = new LambdaQueryWrapper<>();
            //比较id就行，因为还要再比较一个item_type所属对象的类型，这样即可分辨是公寓还是room
            //1.删除原有graphInfoList
            graphVoWrapper.eq(GraphInfo::getItemId, id);
            graphVoWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
            graphInfoService.remove(graphVoWrapper);

            //2.删除原有roomAttrValueList
            LambdaQueryWrapper<RoomAttrValue> attrValueWrapper = new LambdaQueryWrapper<>();
            attrValueWrapper.eq(RoomAttrValue::getRoomId, id);
            roomAttrValueService.remove(attrValueWrapper);

            //3.删除原有roomFacilityList
            LambdaQueryWrapper<RoomFacility> roomFacilityWrapper = new LambdaQueryWrapper<>();
            roomFacilityWrapper.eq(RoomFacility::getRoomId, id);
            roomFacilityService.remove(roomFacilityWrapper);

            //4.删除原有roomLabelList
            LambdaQueryWrapper<RoomLabel> roomLabelWrapper = new LambdaQueryWrapper<>();
            roomLabelWrapper.eq(RoomLabel::getRoomId, id);
            roomLabelService.remove(roomLabelWrapper);

            //5.删除原有paymentTypeList
            LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeWrapper = new LambdaQueryWrapper<>();
            roomPaymentTypeWrapper.eq(RoomPaymentType::getRoomId, id);
            roomPaymentTypeService.remove(roomPaymentTypeWrapper);

            //6.删除原有leaseTermList
            LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermWrapper = new LambdaQueryWrapper<>();
            roomLeaseTermWrapper.eq(RoomLeaseTerm::getRoomId, id);
            roomLeaseTermService.remove(roomLeaseTermWrapper);
        }

        saveOrUpdate(roomSubmitVo);

        //传进来的视图包含了GraphVoList，拿到后判断有没有，再装到自己创建的集合中
        List<GraphVo> graphVos = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVos)) {
            //这个集合不是GraphVo了，而是GraphInfo
            List<GraphInfo> graphInfos = new ArrayList<>();
            for (GraphVo graphVo : graphVos) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemType(ItemType.ROOM);
                graphInfo.setItemId(roomSubmitVo.getId());

                graphInfos.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfos);
        }

        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)) {
            List<RoomAttrValue> roomAttrValues = new ArrayList<>();
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue roomAttrValue = RoomAttrValue.builder().roomId(roomSubmitVo.getId()).attrValueId(attrValueId).build();
                roomAttrValues.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValues);
        }

        //无序操作配套信息本身 只需要操作关联表就行
        //在后台保存更新房屋信息页面也改不了那个 所以整个关联表就行
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<RoomFacility> roomFacilities = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = RoomFacility.builder().roomId(roomSubmitVo.getId()).facilityId(facilityInfoId).build();
                roomFacilities.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilities);
        }

        //通过roomSubmitVo，获取labelInfoIds的id集合
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIds)) {
            //准备关联表对象集合
            List<RoomLabel> roomLabels = new ArrayList<>();
            for (Long labelInfoId : labelInfoIds) {
                //通过vo视图里（roomSubmitVo）的集合（LabelInfoIds）和本身的id 构建一个关联表对象的集合（关联表room  Labels）
                RoomLabel roomLabel = RoomLabel.builder().roomId(roomSubmitVo.getId()).labelId(labelInfoId).build();
                roomLabels.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabels);
            //最后保存了关联表
        }

        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        //查到的id
        if (!CollectionUtils.isEmpty(paymentTypeIds)) {
            //弄链接对象装查到的id
            List<RoomPaymentType> roomPaymentTypes = new ArrayList<>();

            //遍历查到的id
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder().roomId(roomSubmitVo.getId()).paymentTypeId(paymentTypeId).build();
                roomPaymentTypes.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypes);
        }

        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)) {
            ArrayList<RoomLeaseTerm> roomLeaseTerms = new ArrayList<>();
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder().roomId(roomSubmitVo.getId()).leaseTermId(leaseTermId).build();
                roomLeaseTerms.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTerms);
        }
    }

    //根据条件分页查询房间列表
    @Override
    public Page<RoomItemVo> pageRoomItemVO(Page<RoomItemVo> roomItemVoPage, RoomQueryVo queryVo) {
        return baseMapper.selectRoomItemList(roomItemVoPage, queryVo);
    }

    @Override
    public void removeRoomInfoById(Long id) {

        LambdaQueryWrapper<LeaseAgreement> leaseAgreementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        leaseAgreementLambdaQueryWrapper.eq(LeaseAgreement::getRoomId, id).in(LeaseAgreement::getStatus, 2, 5, 7);
        Long count = leaseAgreementMapper.selectCount(leaseAgreementLambdaQueryWrapper);

        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.ROOM_HAS_PEOPLE);
        }

        this.removeById(id);

        //比较id就行，因为还要再比较一个item_type所属对象的类型，这样即可分辨是公寓还是room
        //1.删除原有graphInfoList
        LambdaQueryWrapper<GraphInfo> graphVoWrapper = new LambdaQueryWrapper<>();
        graphVoWrapper.eq(GraphInfo::getItemId, id);
        graphVoWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        graphInfoService.remove(graphVoWrapper);

        //2.删除原有roomAttrValueList
        LambdaQueryWrapper<RoomAttrValue> attrValueWrapper = new LambdaQueryWrapper<>();
        attrValueWrapper.eq(RoomAttrValue::getRoomId, id);
        roomAttrValueService.remove(attrValueWrapper);

        //3.删除原有roomFacilityList
        LambdaQueryWrapper<RoomFacility> roomFacilityWrapper = new LambdaQueryWrapper<>();
        roomFacilityWrapper.eq(RoomFacility::getRoomId, id);
        roomFacilityService.remove(roomFacilityWrapper);

        //4.删除原有roomLabelList
        LambdaQueryWrapper<RoomLabel> roomLabelWrapper = new LambdaQueryWrapper<>();
        roomLabelWrapper.eq(RoomLabel::getRoomId, id);
        roomLabelService.remove(roomLabelWrapper);

        //5.删除原有paymentTypeList
        LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeWrapper = new LambdaQueryWrapper<>();
        roomPaymentTypeWrapper.eq(RoomPaymentType::getRoomId, id);
        roomPaymentTypeService.remove(roomPaymentTypeWrapper);

        //6.删除原有leaseTermList
        LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermWrapper = new LambdaQueryWrapper<>();
        roomLeaseTermWrapper.eq(RoomLeaseTerm::getRoomId, id);
        roomLeaseTermService.remove(roomLeaseTermWrapper);

    }

    @Override
    public RoomDetailVo getRoomInfoById(Long id) {
        RoomInfo roomInfo = this.getById(id);
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(roomInfo, roomDetailVo);

        List<GraphVo> graphVoList = graphInfoMapper.selectGraphVOByApartmentIdAndItemTypeId(id, ItemType.ROOM);
        List<AttrValueVo> attrValueVoList = attrValueMapper.selectAttrValueListByRoomId(id);
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectFacilityInfoListByRoomId(id);
        List<LabelInfo> labelInfoList = labelInfoMapper.selectLabelInfoListByRoomId(id);
        List<PaymentType> paymentTypeList = paymentTypeMapper.selectPaymentTypeListByRoomId(id);
        List<LeaseTerm> leaseTermList = leaseTermMapper.selectLeaseTermByRoomId(id);

        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setAttrValueVoList(attrValueVoList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        roomDetailVo.setLeaseTermList(leaseTermList);

        return roomDetailVo;
    }


}